package com.leiqichao.backend.controller;

import com.leiqichao.backend.common.Result;
import com.leiqichao.backend.entity.Category;
import com.leiqichao.backend.service.CategoryService;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/categories")
public class CategoryController {

    private final CategoryService categoryService;

    public CategoryController(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    /**
     * 获取子分类列表
     * @param parentId 父分类ID（不传默认为0）
     */
    @GetMapping("/children")
    public Result<List<Category>> getChildren(@RequestParam(required = false) Long parentId) {
        return Result.success(categoryService.getChildren(parentId));
    }

    /**
     * 获取完整分类树
     */
    @GetMapping("/tree")
    public Result<List<Category>> getCategoryTree() {
        return Result.success(categoryService.getCategoryTree());
    }

    /**
     * 创建分类
     */
    @PostMapping
    public Result<Category> createCategory(@RequestBody Category category) {
        if (categoryService.createCategory(category)) {
            return Result.success(category);
        }
        return Result.error(500, "创建失败");
    }

    /**
     * 更新分类
     */
    @PutMapping("/{id}")
    public Result<Category> updateCategory(@PathVariable Long id, @RequestBody Category category) {
        category.setId(id);
        if (categoryService.updateCategory(category)) {
            return Result.success(category);
        }
        return Result.error(500, "更新失败");
    }

    /**
     * 删除分类（逻辑删除）
     */
    @DeleteMapping("/{id}")
    public Result<?> deleteCategory(@PathVariable Long id) {
        Category category = categoryService.getById(id);
        if (category == null) {
            return Result.error(404, "分类不存在");
        }
        // 检查是否存在子分类
        if (categoryService.getChildren(id).size() > 0) {
            return Result.error(400, "请先删除子分类");
        }
        return categoryService.removeById(id) ? 
            Result.success(null) : Result.error(500, "删除失败");
    }
}